package utils

import (
	"crypto/tls"
	"hg/config"
	"hg/models"
	"hg/pkg/database"
	"math/rand"
	"strconv"
	"time"

	"gopkg.in/gomail.v2"
)

type NoticeMsg struct {
	Title            string
	Content          string
	OperatorUsername string
	Time             time.Time
}

type EmailNotice struct {
	Address string
	Secret  string
}

type QQNotice struct {
	QQNum string
}

type WechatNotice struct {
	WechatNum string
}

type NoticeInterface interface {
	SendNoticeToUsers(msg *NoticeMsg, users ...*models.Userinfo) error
}

var NoticeManager NoticeInterface

func (e *EmailNotice) SendNoticeToUsers(msg *NoticeMsg, user *models.Userinfo) error {
	config := config.GetConfig()
	subject := msg.Title
	body := msg.Content
	code := GetVerificationCode()
	data := &models.EmailCodes{
		Username: user.Username,
		Code:     code,
		Expiry:   time.Now().Add(300 * time.Second),
	}
	if err := database.InsertCodeToDB(data); err != nil {
		return err
	}
	m := gomail.NewMessage()
	m.SetHeader("From", e.Address)
	m.SetHeader("To", user.Email)
	m.SetHeader("Subject", subject)
	m.SetBody("text/plain", body+strconv.Itoa(code))
	d := gomail.NewDialer(config.EmialHost, config.EmialPort, e.Address, e.Secret)
	d.TLSConfig = &tls.Config{InsecureSkipVerify: true}

	if err := d.DialAndSend(m); err != nil {
		return err
	}

	return nil
}

func (e *QQNotice) SendNoticeToUsers(msg *NoticeMsg, users ...*models.Userinfo) error {
	return nil
}

func (e *WechatNotice) SendNoticeToUsers(msg *NoticeMsg, users ...*models.Userinfo) error {
	return nil
}

func GetVerificationCode() int {
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	code := r.Intn(900000) + 100000
	return code
}
